<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 联系人列表 -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>联系人列表</span>
          </div>
          <el-input
            placeholder="搜索联系人"
            v-model="searchUser"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 10px"
          />
          <el-scrollbar style="height: calc(100vh - 200px)">
            <el-menu
              :default-active="activeUser"
              class="user-list"
              @select="handleSelectUser"
            >
              <el-menu-item
                v-for="user in filteredUsers"
                :key="user.userId"
                :index="user.userId.toString()"
              >
                <el-badge :value="user.unreadCount" :hidden="!user.unreadCount">
                  <span>{{ user.nickName }}</span>
                </el-badge>
              </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 聊天区域 -->
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ currentUser ? currentUser.nickName : '请选择联系人' }}</span>
          </div>
          <div class="chat-container" ref="chatContainer">
            <el-scrollbar style="height: calc(100vh - 300px)">
              <div v-if="currentUser">
                <div
                  v-for="message in messageList"
                  :key="message.messageId"
                  class="message-item"
                  :class="{ 'message-right': message.senderId === userId }"
                >
                  <div class="message-content">
                    <div class="message-time">{{ parseTime(message.createTime) }}</div>
                    <div class="message-text">{{ message.content }}</div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-chat">
                <el-empty description="请选择联系人开始聊天"></el-empty>
              </div>
            </el-scrollbar>
          </div>
          <div class="chat-input" v-if="currentUser">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入消息内容"
              v-model="messageContent"
              @keyup.enter.native="sendMessage"
            />
            <el-button type="primary" @click="sendMessage" style="margin-top: 10px">发送</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listMessage, addMessage, getUnreadCount, readMessage } from "@/api/system/message";
import { listUser } from "@/api/system/user";

export default {
  name: "MessageChat",
  data() {
    return {
      // 当前用户ID
      userId: this.$store.state.user.userId,
      // 搜索用户
      searchUser: "",
      // 当前选中的用户
      activeUser: "",
      // 当前聊天用户
      currentUser: null,
      // 用户列表
      userList: [],
      // 消息列表
      messageList: [],
      // 消息内容
      messageContent: "",
      // 定时器
      timer: null
    };
  },
  computed: {
    // 过滤后的用户列表
    filteredUsers() {
      return this.userList.filter(user => 
        user.nickName.toLowerCase().includes(this.searchUser.toLowerCase())
      );
    }
  },
  created() {
    this.getUserList();
    // 启动定时器，每30秒刷新一次未读消息
    this.timer = setInterval(() => {
      if (this.userList.length > 0) {
        this.getUnreadCount();
      }
    }, 30000);
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 获取用户列表
    getUserList() {
      listUser().then(response => {
        this.userList = response.rows;
        this.getUnreadCount();
      });
    },
    // 获取未读消息数量
    getUnreadCount() {
      this.userList.forEach(user => {
        getUnreadCount(user.userId).then(response => {
          this.$set(user, 'unreadCount', response.data);
        });
      });
    },
    // 选择用户
    handleSelectUser(userId) {
      this.activeUser = userId;
      this.currentUser = this.userList.find(user => user.userId.toString() === userId);
      this.getMessageList();
    },
    // 获取消息列表
    getMessageList() {
      if (!this.currentUser) return;
      
      listMessage({
        senderId: this.userId,
        receiverId: this.currentUser.userId
      }).then(response => {
        this.messageList = response.rows;
        // 将消息标记为已读
        this.messageList.forEach(message => {
          if (message.receiverId === this.userId && message.isRead === "0") {
            readMessage(message.messageId);
          }
        });
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      });
    },
    // 发送消息
    sendMessage() {
      if (!this.messageContent.trim()) {
        this.$message.warning("消息内容不能为空");
        return;
      }
      
      addMessage({
        receiverId: this.currentUser.userId,
        content: this.messageContent
      }).then(response => {
        this.messageContent = "";
        this.getMessageList();
      });
    },
    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.chatContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    }
  }
};
</script>

<style scoped>
.user-list {
  border-right: none;
}

.message-item {
  margin-bottom: 20px;
  display: flex;
}

.message-right {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 10px;
  border-radius: 5px;
  background-color: #f4f4f5;
}

.message-right .message-content {
  background-color: #ecf5ff;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.message-text {
  word-break: break-all;
}

.empty-chat {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-input {
  margin-top: 20px;
}
</style> 